import { _decorator, dragonBones, JsonAsset } from 'cc';
import { app } from 'db://app-game/core/app';
import AnimatorDragonBones from 'db://app-game/libs/animator/AnimatorDragonBones';
import { AnimatorStateLogic } from 'db://app-game/libs/animator/core/AnimatorStateLogic';
import { Role } from '../Role';
import { RoleUpperBodyStateEnum } from '../Role.type';
import { AnimationEventHandler } from './animator/AnimationEventHandler';
import { RoleStateRelease } from './animator/bow/RoleStateRelease';

const { ccclass, requireComponent, disallowMultiple } = _decorator;

/** 角色上半身动画规则管理 */
@ccclass('RoleViewUpperBodyAnimator')
@disallowMultiple
@requireComponent(dragonBones.ArmatureDisplay)
export class RoleViewUpperBodyAnimator extends AnimatorDragonBones {
  /** 角色对象 */
  role: Role = null!;

  protected async start() {
    // 1.获取状态机
    await this.animatorGraph();

    // 2.初始化状态机
    super.start();

    // 3.动画状态机
    let anim = new AnimationEventHandler();
    let asl: Map<string, AnimatorStateLogic> = new Map();
    asl.set(RoleUpperBodyStateEnum.Release, new RoleStateRelease(this.role, anim)); // 射箭释放状态
    asl.set(RoleUpperBodyStateEnum.SkillQuick, new RoleStateSkillQuick(this.role, anim)); // 瞬发技能状态
    this.initArgs(asl, anim);
  }

  /** 初始化状态机参数 */
  async animatorGraph() {
    const animatorGraphPath = this.role.RoleModelJob.roleDragonBones.upperBody.animatorGraphPath;
    const config = await app.res.loadAsync(animatorGraphPath, JsonAsset);
    this.AssetRawUrl = config;
  }

  /**
   * 播放动画
   * @override
   * @param animName 动画名
   * @param loop 是否循环播放
   */
  protected playAnimation(animName: string, loop: boolean) {
    // 1.获取动画名称
    animName = this.getAnimationName(animName);

    // 2.播放动画
    console.log('播放动画：', animName);
    this._dragonBones.playAnimation(animName, loop ? 0 : 1);
  }

  /** 获取动画名称 */
  private getAnimationName(animName: string) {
    // 1.获取武器前缀
    const weaponName = this.role.RoleModelEquipment.weapon.animPrefix;
    return `${weaponName}_${animName}`;
  }
}
